package com.misalen.retrofit.converter.response;

import java.io.IOException;
import org.json.JSONObject;
import com.google.gson.TypeAdapter;
import okhttp3.ResponseBody;
import retrofit2.Converter;

public final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
	// private final Gson gson;
	private final TypeAdapter<T> adapter;

	public GsonResponseBodyConverter(TypeAdapter<T> adapter) {
		// this.gson = gson;
		this.adapter = adapter;
	}

	@Override
	public T convert(ResponseBody value) throws IOException {
		try {

			JSONObject object = new JSONObject(value.string());
			if (object.getInt("errorCode") == 200) {
				return adapter.fromJson(object.getString("data"));
			} else {
				throw new IOException(object.getString("message"));
			}

		} finally {
			value.close();
		}
	}
}
